package controllers;

import models.TimeUser;
import play.Logger;
import play.data.validation.Valid;
import play.mvc.Catch;
import play.mvc.Controller;

import com.google.gson.JsonObject;

public class TimeUserManager extends Controller {

	public static void index() {
		render();
	}

	public static void list() {
		renderJSON(TimeUser.all().fetch());
	}

	public static void create(@Valid TimeUser user) {
		if (validation.hasErrors()) {
			sendresult(false);
		} else {
			try {
				user.save();
				renderJSON(user);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				sendresult(false);
			}
		}
	}

	public static void edit(String tagid) {
		try {
			TimeUser user = TimeUser.findByTag(tagid);
			renderJSON(user);
		} catch (Exception e) {
			sendresult(false);
		}
	}

	public static void save(@Valid TimeUser user) {
		try {
			user.save();
			renderJSON(user);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			sendresult(false);
		}
	}

	public static void newUser() {
		renderJSON(new TimeUser());
	}

	public static void delete(String tagid) {
		try {
			TimeUser.findByTag(tagid).delete();
			sendresult(true);
		} catch (Exception exp) {
			sendresult(false);
		}
	}

	public static void sendresult(boolean success) {
		JsonObject res = new JsonObject();
		res.addProperty("success", success);
		renderJSON(res.toString());
	}

	@Catch
	private static void exceptions(Exception e) {
		Logger.info("Exceptions " + e.getMessage());
		sendresult(false);
	}
}
